<?php

if (isset($_POST['action'])) {
    define('SUBSIDY', 8);
    $action = $_POST['action'];
    switch ($action) {
        case 'getRoute':
            require_once './classes/RouteStation.php';
            $sr = new RouteStation();
            $route = $sr->getRoute();
            header('Content-Type: application/json');
            if ($route) {
                $result = array(
                    'error' => false,
                    'message' => $route
                );
                echo json_encode($result);
            } else {
                $result = array(
                    'error' => false,
                    'message' => 'No route found, please contact administrator.'
                );
                echo json_encode($result);
            }
            break;
        case 'getOrigin':
            require_once './classes/RouteStation.php';
            $sr = new RouteStation();
            $origin = $sr->getOrigin();
            header('Content-Type: application/json');
            if ($origin) {
                $result = array(
                    'error' => false,
                    'message' => $origin
                );
                echo json_encode($result);
            } else {
                $result = array(
                    'error' => false,
                    'message' => 'No route found, please contact administrator.'
                );
                echo json_encode($result);
            }
            break;
        case 'getDestin':
            require_once './classes/RouteStation.php';
            $sr = new RouteStation();
            $destin = $sr->getDestination();
            header('Content-Type: application/json');
            if ($destin) {
                $result = array(
                    'error' => false,
                    'message' => $destin
                );
                echo json_encode($result);
            } else {
                $result = array(
                    'error' => false,
                    'message' => 'No route found, please contact administrator.'
                );
                echo json_encode($result);
            }
            break;
        case 'obtainSchedule':
            require_once 'classes/Schedule.php';
            require_once 'classes/Seat.php';
            require_once 'classes/Utilities.php';
            $date = trim($_POST['date']);
            $s = new Schedule();
            $seat = new Seat();
            $schedule = $s->obtainSchedules();
            $emptyseat = 0;
            $button = '<input type="button" value="Proceed" class="small button right" onclick=\'proceedBooking();\'>';
            header('Content-Type: application/json');
            if ($schedule != null) {
                $timetable = '<input type="hidden" name="date" value="' . $date . '"/>
                    <input type="hidden" id="action" value="proceedBooking"/>
                    <table><thead><tr><th></th><th>Route Name</th><th>Schedule Name</th><th>Origin</th>
                    <th>Destination</th><th>Departure</th><th>Arrival</th></tr></thead><tbody><tr>';
                for ($x = 0; $x < count($schedule['origin']); $x++) {
                    $emptyseat = $seat->getNoOfEmptySeat($date, $schedule['origin'][$x]['scheduleid']);
                    if ($schedule['origin'][$x]['fare'] != 0) {
                        $totalfare = ($schedule['destin'][$x]['fare'] - $schedule['origin'][$x]['fare']) + SUBSIDY;
                    } else {
                        $totalfare = $schedule['destin'][$x]['fare'];
                    }
                    $departure = Utilities::calculateTime($date, $schedule['origin'][$x]['departureTime'], $schedule['origin'][$x]['travelTime']);
                    $arrival = Utilities::calculateTime($date, $schedule['destin'][$x]['departureTime'], $schedule['destin'][$x]['travelTime']);
                    $timetable .= '<input type="hidden" id="shid' . $x . '" value="' . $schedule['origin'][$x]['scheduleid'] . '">
                        <td><input type="radio" value="' . $x . '" name="index" 
                    onchange=\'$("tr[id]").addClass("hidden-field");$("#' . $x . '").removeClass("hidden-field");\'/></td>';
                    $timetable .= '<td><input type="hidden" value="' . $schedule['origin'][$x]['routeName'] .
                            '" id="route' . $x . '"/>' . $schedule['origin'][$x]['routeName'] . '</td>';
                    $timetable .= '<td><input type="hidden" value="' . $schedule['origin'][$x]['scheduleName'] .
                            '" id="schedule' . $x . '"/>' . $schedule['origin'][$x]['scheduleName'] . '</td>';
                    $timetable .= '<td><input type="hidden" value="' . $schedule['origin'][$x]['origin'] .
                            '" id="origin' . $x . '"/>' . $schedule['origin'][$x]['origin'] . '</td>';
                    $timetable .= '<td><input type="hidden" value="' . $schedule['destin'][$x]['destin'] .
                            '" id="destin' . $x . '"/>' . $schedule['destin'][$x]['destin'] . '</td>';
                    $timetable .= '<td><input type="hidden" value="' . date('H:i:s', $departure) .
                            '" id="departure' . $x . '"/>' . date('Y-m-d H:i:s', $departure) . '</td>';
                    $timetable .= '<td><input type="hidden" value="' . date('H:i:s', $arrival) .
                            '" id="arrival' . $x . '"/>' . date('Y-m-d H:i:s', $arrival) . '</td>';
                    $timetable .= '</tr>
                               <tr id="' . $x . '" class="hidden-field">
                                   <td colspan="7">
                                       <div class="row">
                                       <div class="small-8 small-offset-2 columns">
                                       <table style="width:100%">
                                           <tr>
                                               <td style="width: 200px">Avaliable Seat</td>
                                               <td>:</td>
                                               <td><input type="hidden" id="seat' . $x . '" value="' . $emptyseat . '"/>' . $emptyseat . '</td>
                                           </tr>
                                           <tr>
                                               <td>Fare</td>
                                               <td>:</td>
                                               <td><input type="hidden" id="fare' . $x . '" value="' . $totalfare . '"/>RM ' . number_format($totalfare, 2) . '</td>
                                           </tr>
                                       </table>';
                    if ($emptyseat != 0) {
                        $timetable .= $button;
                    }
                    $timetable .= '</div></div></td></tr >';
                }
                $timetable .= '</tbody>
                            </table>';

                $result = array(
                    'error' => false,
                    'message' => $timetable
                );
                echo json_encode($result);
            } else {
                $result = array(
                    'error' => true,
                    'message' => 'Schedule not found.'
                );
                echo json_encode($result);
            }
            break;
        case 'proceedBooking':
            require_once 'classes/Member.php';
            require_once 'classes/Discountrate.php';
            session_start();
            $m = new Member();
            $balance = $m->checkBalance($_SESSION['uid']);
            header('Content-Type: application/json');
            if ($balance > 50) {
                unset($_POST['action']);
                $d = new Discountrate();
                $discount = $d->getDiscountrate();
                if ($discount) {
                    $_SESSION['discount'] = array(
                        'did' => $discount['did'],
                        'rate' => $discount['rate']
                    );
                } else {
                    $_SESSION['discount'] = array(
                        'did' => 1,
                        'rate' => 1.0
                    );
                }
                $_SESSION['ticketdetails'] = serialize($_POST);
                $result = array(
                    'error' => false,
                    'message' => 'Sufficient balance'
                );
                echo json_encode($result);
            } else {
                $result = array(
                    'error' => true,
                    'message' => 'You have insufficient balance in your account, please reload first and make sure to have RM50 and above.'
                );
                echo json_encode($result);
            }
            break;
        case 'generateTicketTemplete':
            session_start();
            require_once 'classes/Member.php';
            header('Content-Type: application/json');
            $member = new Member();
            $balance = $member->checkBalance($_SESSION['uid']);
            $_SESSION['balance'] = $balance;
            $n = trim($_POST['number']);
            $data = unserialize($_SESSION['ticketdetails']);
            $purchaselimit = 10;
            $maxfare = $data['fare'] * $n;
            $submit = '<hr/><input type="hidden" id="discount" value="' . $_SESSION['discount']['rate'] . '"><input type="button" value="Submit" onclick=\'createTicket();\' class="button small right" />';
            $ticket = '';
            if ($n > $purchaselimit) {
                $ticket .= 'You can only buy max 10 tickets for each transaction';
                $tickets = array(
                    'error' => true,
                    'forms' => $ticket
                );
                echo json_encode($tickets);
            } else {
                if (isset($_SESSION['coupon'])) {
                    $maxfare -= $_SESSION['coupon']['value'];
                }
                if ($balance < $maxfare) {
                    $ticket .= 'You have insufficient credit to purchase ' . $n . ' ticket(s)';
                    $tickets = array(
                        'error' => true,
                        'forms' => $ticket
                    );
                    echo json_encode($tickets);
                } else {
                    for ($x = 1; $x <= $n; $x++) {
                        $ticket .= '<form id="ticket' . $x . '" class="postable custom">' .
                                '<input type="hidden" id="seatid' . $x . '"name="seatid"/>' .
                                '<input type="hidden" name="action" value="createTicket"/>' .
                                '<div class="row">' .
                                '<div class="large-2 left columns">' .
                                '<label class="inline">Ticket No.' . $x . '</label>' .
                                '</div>' .
                                '<div class="large-4 left columns">' .
                                '<label class="inline">Select passenger type: </label>' .
                                '</div>' .
                                '<div class="large-2 left columns">' .
                                '<select id="type' . $x . '"name="type">' .
                                '<option value="1.0">Adult</option>' .
                                '<option value="0.8">Child</option>' .
                                '</select>' .
                                '</div>' .
                                '<div class="large-2 left columns">' .
                                '<label class="inline">Choose seat:</label>' .
                                '</div>' .
                                '<div class="large-2 left columns">' .
                                '<input type="text" id="seatno' . $x . '" onclick=\'showModal(this);\' readonly/>' .
                                '</div>' .
                                '</div>' .
                                '</form>';
                    }
                    $ticket .= $submit;
                    $tickets = array(
                        'error' => false,
                        'forms' => $ticket
                    );
                    echo json_encode($tickets);
                }
            }
            break;
        case 'getCoachmap':
            require_once 'classes/Seat.php';
            session_start();
            $data = unserialize($_SESSION['ticketdetails']);
            $coach = trim($_POST['coach']);
            $allavailable = true;
            $y = 0;
            $z = 0;
            $s = new Seat();
            $bookedseat = $s->getBookedSeat($data['date'], $data['shid'], $coach);
            $coachmap = $s->getCoachmap($coach);
            if (isset($_SESSION['seat'])) {
                $lockedseat = $_SESSION['seat'];
                $allavailable = false;
            } else {
                $lockedseat = null;
            }
            if ($bookedseat != null) {
                $available = array_intersect($coachmap, $bookedseat);
                $allavailable = false;
            } else {
                $available = NULL;
            }
            switch ($coach) {
                case 'A':
                    $z = 1;
                    $y = 57;
                    break;
                case 'B':
                    $z = 57;
                    $y = 113;
                    break;
                case 'C':
                    $z = 113;
                    $y = 169;
                    break;
                case 'D':
                    $z = 169;
                    $y = 225;
                    break;
                case 'E':
                    $z = 225;
                    $y = 281;
                    break;
                case 'F':
                    $z = 281;
                    $y = 337;
                    break;
            }
            $table = '<table style="width: 100%;text-align: center"><tr>';
            $index = 0;
            for ($x = $z; $x < $y; $x++) {
                if (!$allavailable) {
                    if ($available != null) {
                        if (in_array($x, $available)) {
                            $table .= '<td style="width:112px"><img src="img/SeatBooked.png"/><br/>' . $s->getSeatNo($coachmap[$index]) . '</td>';
                        } else {
                            if ($lockedseat != null) {
                                if (in_array($x, $lockedseat)) {
                                    $table .= '<td style="width:112px"><img src="img/SeatLocked.png"/><br/>' . $s->getSeatNo($coachmap[$index]) . '</td>';
                                } else {
                                    $table .= '<td style="width:112px"><a id="' . $x . '" onclick=\'getSeatid(this, "' . $s->getSeatNo($coachmap[$index]) . '", "' . $coach . '");\'><img src="img/SeatAvailable.png"/></a><br/>' . $s->getSeatNo($coachmap[$index]) . '</td>';
                                }
                            } else {
                                $table .= '<td style="width:112px"><a id="' . $x . '" onclick=\'getSeatid(this, "' . $s->getSeatNo($coachmap[$index]) . '", "' . $coach . '");\'><img src="img/SeatAvailable.png"/></a><br/>' . $s->getSeatNo($coachmap[$index]) . '</td>';
                            }
                        }
                    } else {
                        if ($lockedseat != null) {
                            if (in_array($x, $lockedseat)) {
                                $table .= '<td style="width:112px"><img src="img/SeatLocked.png"/><br/>' . $s->getSeatNo($coachmap[$index]) . '</td>';
                            } else {
                                $table .= '<td style="width:112px"><a id="' . $x . '" onclick=\'getSeatid(this, "' . $s->getSeatNo($coachmap[$index]) . '", "' . $coach . '");\'><img src="img/SeatAvailable.png"/></a><br/>' . $s->getSeatNo($coachmap[$index]) . '</td>';
                            }
                        } else {
                            $table .= '<td style="width:112px"><a id="' . $x . '" onclick=\'getSeatid(this, "' . $s->getSeatNo($coachmap[$index]) . '", "' . $coach . '");\'><img src="img/SeatAvailable.png"/></a><br/>' . $s->getSeatNo($coachmap[$index]) . '</td>';
                        }
                    }
                } else {
                    $table .= '<td style="width:112px"><a id="' . $x . '" onclick=\'getSeatid(this, "' . $s->getSeatNo($coachmap[$index]) . '", "' . $coach . '");\'><img src="img/SeatAvailable.png"/></a><br/>' . $s->getSeatNo($coachmap[$index]) . '</td>';
                }
                if ($x % 2 == 0) {
                    if ($x % 4 == 0) {
                        $table .= '';
                    } else {
                        $table .= '<td style="width:50px"></td>';
                    }
                }
                if ($x % 4 == 0) {
                    $table .= '</tr><tr>';
                }
                $index++;
            }
            echo $table;
            break;
        case 'getCoach':
            require_once 'classes/Seat.php';
            $seat = new Seat();
            $coach = $seat->getCoach();
            header('Content-Type: application/json');
            echo json_encode($coach);
            break;
        case 'lockSeat':
            session_start();
            $id = trim($_POST['id']);
            $_SESSION['seat'][] = $id;
            break;
        case 'unlockSeat':
            session_start();
            $seat = $_SESSION['seat'];
            $id = trim($_POST['id']);
            for ($i = 0; $i < count($seat); $i++) {
                if ($seat[$i] == $id) {
                    unset($_SESSION['seat'][$i]);
                    break;
                }
            }
            break;
        case 'createTicket':
            require_once 'classes/Ticket.php';
            require_once 'classes/Member.php';
            require_once 'classes/Seat.php';
            session_start();
            $data = unserialize($_SESSION['ticketdetails']);
            $seatno = trim($_POST['seatid']);
            $passenger = trim($_POST['type']);
            $fare = $data['fare'];
            $fare *= $passenger;
            $fare *= $_SESSION['discount']['rate'];
            if (isset($_SESSION['total'])) {
                $_SESSION['total'] += $fare;
            } else {
                $_SESSION['total'] = 0 + $fare;
            }
            $ticket = new Ticket();
            $m = new Member();
            $icno = $m->getMemberIC($_SESSION['uid']);
            $id = $ticket->generateTicket($data['date'], $data['departure'], $data['arrival'], $data['origin'], $data['destin'], $data['schedule'], $fare, 'PAD', $icno, $_SESSION['discount']['did'], $data['shid']);
            if ($id != null) {
                $seat = new Seat();
                $_SESSION['qrcode'][] = $id['qrcode'];
                $result = $seat->bookSeat($data['shid'], $seatno, 'BKD', $data['date'], $id['reference']);
                if ($result) {
                    $result = array(
                        'error' => false,
                        'fare' => $_SESSION['total']
                    );
                } else {
                    $result = array(
                        'error' => true,
                        'fare' => $_SESSION['total']
                    );
                }
            } else {
                $result = array(
                    'error' => true,
                    'fare' => $_SESSION['total']
                );
            }
            header('Content-Type: application/json');
            echo json_encode($result);
            break;
        case 'makePayment':
            require_once 'classes/Member.php';
            require_once 'classes/RedeemItem.php';
            session_start();
            header('Content-Type: application/json');
            $fare = $_SESSION['total'];
            $balance = $_SESSION['balance'];
            $point = floor(($fare / 10));
            $m = new Member();
            $ri = new RedeemItem();
            $gotcoupon = false;
            if (isset($_SESSION['coupon'])) {
                $coupon = trim($_SESSION['coupon']['value']);
                $fare -= $coupon;
                $gotcoupon = true;
                if ($fare < 0) {
                    $fare = 0;
                }
            }
            if ($fare != 0) {
                $newbalance = $balance - $fare;
                $update = $m->deduceBalance($newbalance, $_SESSION['uid']);
                if ($update) {
                    if ($gotcoupon) {
                        $ri->updateCouponStatus($_SESSION['coupon']['referenceno']);
                    }
                    $m->addPoint($point, $_SESSION['uid']);
                    $result = array(
                        'error' => false
                    );
                    echo json_encode($result);
                } else {
                    $result = array(
                        'error' => true,
                        'message' => 'Something went wrong, please try again later.'
                    );
                    echo json_encode($result);
                }
            } else {
                if ($gotcoupon) {
                    $ri->updateCouponStatus($_SESSION['coupon']['referenceno']);
                }
                $m->addPoint($point, $_SESSION['uid']);
                $result = array(
                    'error' => false
                );
                echo json_encode($result);
            }
            break;
        case 'addSalesLog':
            session_start();
            require_once 'classes/Logs.php';
            $log = new Logs();
            $amount = trim($_POST['total']);
            $type = trim($_POST['type']);
            $madeby = $_SESSION['uid'];
            $log->insertSalesLog($amount, $madeby, $type);
            break;
        case 'cleanUp':
            session_start();
            unset($_SESSION['total']);
            unset($_SESSION['balance']);
            unset($_SESSION['ticketdetails']);
            unset($_SESSION['seat']);
            unset($_SESSION['coupon']);
            unset($_SESSION['discount']);
            break;
        case 'backCleanUp':
            session_start();
            unset($_SESSION['total']);
            unset($_SESSION['balance']);
            unset($_SESSION['ticketdetails']);
            unset($_SESSION['seat']);
            unset($_SESSION['coupon']);
            unset($_SESSION['discount']);
            break;
        case 'checkCoupon':
            session_start();
            require_once 'classes/RedeemItem.php';
            $ri = new RedeemItem();
            $value = $ri->checkCoupon();
            header('Content-Type: application/json');
            if ($value) {
                if ($value['status'] == 'UNUSED') {
                    if (substr($value['itemcode'], 0, 3) == 'CPN') {
                        $_SESSION['coupon'] = $value;
                        $result = array(
                            'error' => false,
                            'message' => 'Coupon successfully used.',
                            'value' => $value['value']
                        );
                    } else {
                        $result = array(
                            'error' => true,
                            'message' => 'This is not a coupon. Please check again.'
                        );
                    }
                } else {
                    $result = array(
                        'error' => true,
                        'message' => 'This coupon has already been used.'
                    );
                }
            } else {
                $result = array(
                    'error' => true,
                    'message' => 'Invalid coupon, did you enter the correct coupon number?'
                );
            }
            echo json_encode($result);
            break;
        case 'getRedeemableItem':
            session_start();
            require_once 'classes/RedeemItem.php';
            require_once 'classes/Member.php';
            header('Content-Type: application/json');
            $ri = new RedeemItem();
            $m = new Member();
            $point = $m->checkPoint($_SESSION['uid']);
            if (isset($_POST['type'])) {
                $data = $ri->getFilteredItem();
            } else {
                $data = $ri->getAllRedeemableItem();
            }
            if ($data) {
                $message = '';
                for ($i = 0; $i < count($data); $i++) {
                    $message .= '<div class="large-4 columns left">' .
                            '<ul class="pricing-table">' .
                            '<li class="title">' . $data[$i]['itemcode'] . '</li>' .
                            '<li class="price">' . $data[$i]['pointrequired'] . ' pts</li>' .
                            '<li class="description">' . $data[$i]['itemname'] . '</li>';
                    if ($data[$i]['itemimage'] != null) {
                        $message .= '<li class="bullet-item"><img style="height: 150px" src="' . $data[$i]['itemimage'] . '"/></li>';
                    }
                    if ($point >= $data[$i]['pointrequired']) {
                        $message .= '<li class="cta-button"><input type="button" class="small button" onclick=\'redeemItem("' . $data[$i]['itemcode'] . '",' . $data[$i]['pointrequired'] . ');\' value="Redeem"/></li>';
                    } else {
                        $message .= '<li class="cta-button"><input type="button" class="small button" value="Redeem" disabled/></li>';
                    }
                    $message .= '</ul></div>';
                }
                $result = array(
                    'error' => false,
                    'message' => $message
                );
            } else {
                $result = array(
                    'error' => true,
                    'message' => 'No item found in this category.'
                );
            }
            echo json_encode($result);
            break;
        case 'redeemItem':
            session_start();
            require_once 'classes/RedeemItem.php';
            require_once 'classes/Member.php';
            header('Content-Type: application/json');
            $point = $_POST['point'];
            $type = substr($_POST['itemcode'], 0, 3);
            $ri = new RedeemItem();
            $m = new Member();
            $success = $ri->redeemItem();
            if ($success != null) {
                if ($type == 'CRD') {
                    $message = 'Item successfully redeemed, the redeemed credit has been credited to your account.';
                } else {
                    $message = 'Item successfully redeemed, your reference number is :<br/>' . $success . '.';
                }
                $newpoint = $m->deducePoint($point, $_SESSION['uid']);
                $result = array(
                    'error' => false,
                    'message' => $message,
                    'point' => $newpoint
                );
            } else {
                $result = array(
                    'error' => false,
                    'message' => 'Unable to redeem now, please try again later.'
                );
            }
            echo json_encode($result);
            break;
        case 'getHistory':
            require_once 'classes/RedeemItem.php';
            header('Content-Type: application/json');
            $ri = new RedeemItem();
            $data = $ri->getRedeemHistory();
            if ($data) {
                $message = '<table class=\'footable toggle-arrow-small\'><thead><th style=\'width: 330px\'>' .
                        'Reference No</th><th data-hide=\'phone\'>Item Code</th><th data-hide=\'phone\'>' .
                        'Redeemed Date</th><th data-hide=\'phone\'>Status</th></thead><tbody>';
                foreach ($data as $history) {
                    $message .= '<tr>';
                    $message .= '<td>'. (substr($history['itemcode'], 0, 1) == "S" ?'<a onclick=\'showQRCode("'.$history['referenceno'].'");\'>' : '') . $history['referenceno'] . '</a></td>';
                    $message .= '<td>' . $history['itemcode'] . '</td>';
                    $message .= '<td>' . $history['redeemdate'] . '</td>';
                    $message .= '<td>' . $history['status'] . '</td>';
                    $message .= '</tr>';
                }
                $message .= '</tbody>' .
                        '<tfoot>' .
                        '<tr>' .
                        '<td colspan="4">' .
                        '<div class="pagination pagination-centered hide-if-no-paging"></div>' .
                        '</td>' .
                        '</tr>' .
                        '</tfoot></table>';
                $result = array(
                    'error' => false,
                    'message' => $message
                );
            } else {
                $result = array(
                    'error' => true,
                    'message' => '<p>No redemption history found.</p>'
                );
            }
            echo json_encode($result);
            break;
        case 'cancelTicket':
            require_once 'classes/Ticket.php';
            $oneday = 24 * 60 * 60;
            $twoday = $oneday * 2;
            $threeday = $oneday * 3;
            $reference = trim($_POST['referenceno']);
            $ticket = new Ticket();
            $data = $ticket->getCancellationDetails($reference);
            if ($data['status'] != 'PAD') {
                $result = array(
                    'error' => true,
                    'message' => 'This ticket cannot be cancel as it has been amended once or cancelled before.'
                );
            } else {
                session_start();
                $refund = 0.0;
                $now = time();
                $departure = $data['departure'];
                $range = $departure - $now;
                switch ($range) {
                    case $range > $threeday:
                        $refund = $data['fare'] * 0.75;
                        $result = array(
                            'error' => false,
                            'message' => 'You are eligible for refund with 75% of the ticket&#39;s fare',
                            'refund' => $refund
                        );
                        break;
                    case $range > $twoday && $range < $threeday:
                        $refund = $data['fare'] * 0.50;
                        $result = array(
                            'error' => false,
                            'message' => 'You are eligible for refund with 50% of the ticket&#39;s fare',
                            'refund' => $refund
                        );
                        break;
                    case $range > $oneday && $range < $twoday;
                        $refund = $data['fare'] * 0.25;
                        $result = array(
                            'error' => false,
                            'message' => 'You are eligible for refund with 25% of the ticket&#39;s fare',
                            'refund' => $refund
                        );
                        break;
                    case $range < $oneday && $range >= 0:
                        $result = array(
                            'error' => true,
                            'message' => 'This ticket&#39;s departure time is less than 24 hours from now, thus it&#39;s not eligible for refund.'
                        );
                        break;
                    default:
                        $result = array(
                            'error' => true,
                            'message' => 'This ticket&#39;s departure time was before today, thus it was not eligible for refund.'
                        );
                        break;
                }
                $_SESSION['cancellation'] = $result;
                $_SESSION['reference'] = $reference;
            }
            break;
        case 'confirmCancellation':
            session_start();
            header('Content-Type: application/json');
            require_once 'classes/Seat.php';
            require_once 'classes/Logs.php';
            require_once 'classes/Ticket.php';
            require_once 'classes/Member.php';
            $reference = trim($_POST['reference']);
            $refund = trim($_POST['refund']);
            $s = new Seat();
            $l = new Logs();
            $t = new Ticket();
            $m = new Member();
            $result = array(
                'refund' => false,
                'balance' => 0,
                'referenceno' => $reference
            );
            if ($t->cancelTicket($reference)) {
                if ($l->insertRefundLog($reference, $refund)) {
                    if ($m->updateBalance($refund, $_SESSION['uid'])) {
                        $result = array(
                            'refund' => true,
                            'balance' => $m->checkBalance($_SESSION['uid']),
                            'referenceno' => $reference
                        );
                    }
                }
            }
            echo json_encode($result);
            break;
        case 'amendTicket':
            session_start();
            require_once 'classes/Schedule.php';
            $_SESSION['amendment']['referenceno'] = $_POST['referenceno'];
            $schedule = new Schedule();
            $details = $schedule->getRouteAndStationInfo(trim($_POST['route']), trim($_POST['origin']), trim($_POST['destin']));
            $_SESSION['amendment']['rid'] = $details['rid'];
            $_SESSION['amendment']['originid'] = $details['originid'];
            $_SESSION['amendment']['destinid'] = $details['destinid'];
            break;
        case 'proceedAmend':
            session_start();
            unset($_POST['action']);
            $_SESSION['ticketdetails'] = serialize($_POST);
            echo '<div class=\'row\'>' .
            '<div class=\'large-5 columns\'>' .
            '<label class=\'inline\'>Select your seat</label>' .
            '</div>' .
            '<div class=\'large-3 columns\'>' .
            '<input type="text" id="seatno" onclick=\'showModal(this);\' readonly/>' .
            '</div>' .
            '<div class=\'large-4 columns\'>' .
            '<input type="button" value="Amend" class=\'button small left\' onclick=\'confirmAmendment();\'/>' .
            '</div>' .
            '</div>';
            break;
        case 'confirmAmendment':
            session_start();
            require_once 'classes/Ticket.php';
            require_once 'classes/Seat.php';
            header('Content-Type: application/json');
            $data = unserialize($_SESSION['ticketdetails']);
            $referenceno = trim($_POST['reference']);
            $seatid = trim($_POST['seatid']);
            $s = new Seat();
            $t = new Ticket();
            $result = array(
                'amend' => false,
                'referenceno' => $referenceno,
                'qrcode' => ''
            );
            $salt = "A3/-osv$0-231@#SC34zsd8fq]tj34&41dsjyj70u2%7vw4>[:l-==";
            $param = $referenceno . ' ' . $data['date'] . ' ' . $data['departure'] . ' ' . $data['arrival'] . ' ' . $data['origin'] . ' ' . $data['destin'] . ' ' . $data['schedule'] . ' ' . $data['fare'];
            $rehash = hash('sha256', $salt . $param);
            if ($t->amendTicket($data['date'], $data['departure'], $data['arrival'], $data['schedule'], $data['shid'], $referenceno)) {
                if ($s->amendBookedSeat($data['shid'], $seatid, $data['date'], $referenceno)) {
                    if ($t->updateQRCode($rehash, $referenceno)) {
                        $result = array(
                            'amend' => true,
                            'referenceno' => $referenceno,
                            'qrcode' => $rehash
                        );
                    }
                }
            }
            echo json_encode($result);
            break;
        case 'addNewPost':
            session_start();
            require_once 'classes/Forum.php';
            header('Content-Type: application/json');
            $threadID = $_POST['threadId'];
            $userId = $_SESSION['uid'];
            $comment = $_POST['comment'];
            $p = new Forum();
            if ($p->checkUserPostStatus($_SESSION['uid'])) {
                if ($p->insertPost($threadID, $userId, $comment)) {
                    $result = array(
                        'error' => false,
                        'message' => 'You have post successfully',
                    );
                } else {
                    $result = array(
                        'error' => true,
                        'message' => 'Post is not successful',
                    );
                }
            } else {
                $result = array(
                    'error' => true,
                    'message' => 'You are not allow to post'
                );
            }

            echo json_encode($result);
            break;
        case 'modifyPost':
            session_start();
            require_once 'classes/Forum.php';
            header('Content-Type: application/json');
            $pid = $_POST['pid'];
            $message = $_POST['message'];
            $p = new Forum();
            if ($p->checkUserPostStatus($_SESSION['uid'])) {
                if ($p->modifyPost($pid, $message)) {
                    $result = array(
                        'error' => false,
                        'message' => 'You have successfully edit the post',
                    );
                } else {
                    $result = array(
                        'error' => true,
                        'message' => 'Post is not successful edit',
                    );
                }
            } else {
                $result = array(
                    'error' => true,
                    'message' => 'You are not allow to edit post'
                );
            }

            echo json_encode($result);
            break;
        case 'banUser':
            session_start();
            require_once 'classes/Forum.php';
            header('Content-Type: application/json');
            $uid = $_POST['uid'];
            $f = new Forum();
            if ($f->banUser($uid)) {
                $result = array(
                    'error' => false,
                    'message' => 'You have successfully ban the user'
                );
            } else {
                $result = array(
                    'error' => true,
                    'message' => 'Some unexpected technical problem occur'
                );
            }
            echo json_encode($result);
            break;
        case 'unbanUser':
            session_start();
            require_once 'classes/Forum.php';
            header('Content-Type: application/json');
            $uid = $_POST['uid'];
            $f = new Forum();
            if ($f->unBanUser($uid)) {
                $result = array(
                    'error' => false,
                    'message' => 'You have successfully unban the user'
                );
            } else {
                $result = array(
                    'error' => true,
                    'message' => 'Some unexpected technical problem occur'
                );
            }
            echo json_encode($result);
            break;
        case 'addNewThread':
            session_start();
            require_once 'classes/Forum.php';
            header('Content-Type: application/json');
            $uid = $_SESSION['uid'];
            $fid = $_POST['forumId'];
            $title = $_POST['title'];
            $comment = $_POST['comment'];
            $f = new Forum();
            $newthreadId = $f->getNewThreadID2();

            if ($f->createThread($fid, $uid, $title, $comment)) {
                $result = array(
                    'error' => false,
                    'message' => 'You have successfully create a thread',
                    'threadid' => $newthreadId
                );
            } else {
                $result = array(
                    'error' => true,
                    'message' => 'Something unexpected encounter, Please contact the administrator',
                );
            }
            echo json_encode($result);
            break;
        case 'addNewAnnouncement':
            session_start();
            require_once 'classes/Announcement.php';
            header('Content-Type: application/json');
            print_r($_POST);
            $title = $_POST['title'];
            $message = $_POST['message'];
            $type = $_POST['type'];
            $aa = $_POST['imgFile']['name'];
            //$image = $_POST['imgFile'];
            //$image =($_FILES['photo']['name']); 
            $videoLink = $_POST['videoLink'];
            $uid = $_SESSION['uid'];

            $ann = new Announcement();
            $aid = $ann->getNewAnnouncementId();
            $target = "/upload/" . $aid . "/" . $_POST['imgName'];
            $url = "C:\xampp\htdocs\RailwayWeb\upload\\" + $aid + "\\";
            $tmp = 'C:\xampp\htdocs\RailwayWeb\upload';
            $status = 'Available';

            if ($ann->createAnnouncment($title, $message, $uid, $type, $target, $videoLink, $status)) {
                $result = array(
                    'error' => false,
                    'message' => 'You have successfully post the announcmenet',
                );
            } else {
                $result = array(
                    'error' => true,
                    'message' => 'Something unexpected encounter, Please contact the administrator',
                );
            }
            echo json_encode($result);

            break;
        case 'modifyAnnouncement':
            session_start();
            require_once 'classes/Announcement.php';
            header('Content-Type: application/json');
            $id = $_POST['anID'];
            $title = $_POST['title'];
            $message = $_POST['message'];
            $type = $_POST['type'];
            $target = "upload/" . $id . "/" . $_POST['imgName'];
            $vLink = $_POST['videoLink'];
            $a = new Announcement();
            if ($a->updateAnnouncement($title, $message, $type, $target, $vLink, $id)) {
                $result = array(
                    'error' => false,
                    'message' => 'You have successfully update the announcement details'
                );
            } else {
                $result = array(
                    'error' => true,
                    'message' => 'You must edit/change the details to update'
                );
            }

            echo json_encode($result);
            break;
        case 'deleteAnnouncement':
            session_start();
            require_once 'classes/Announcement.php';
            header('Content-Type: application/json');
            $counts = $_POST['totalSelect'];
            $arrayChkBox = $_POST['c'];
            $ann = new Announcement();
            $result = array();
            for ($i = 0; $i < $counts; $i++) {
                if ($ann->deleteAnnouncement($arrayChkBox[$i])) {
                    $result = array(
                        'error' => false,
                        'message' => 'You have successfully deleted the announcement',
                    );
                } else {
                    $result = array(
                        'error' => true,
                        'message' => 'Something unexpected encounter, Please contact the administrator'
                    );
                }
            }
            echo json_encode($result);
            break;
        case 'restoreAnnouncement':
            session_start();
            require_once 'classes/Announcement.php';
            header('Content-Type: application/json');
            $counts = $_POST['totalSelect'];
            $arrayChkBox = $_POST['c'];
            $ann = new Announcement();
            $result = array();
            for ($i = 0; $i < $counts; $i++) {
                if ($ann->restoreAnnouncement($arrayChkBox[$i])) {
                    $result = array(
                        'error' => false,
                        'message' => 'You have successfully restore the announcement',
                    );
                } else {
                    $result = array(
                        'error' => true,
                        'message' => 'Something unexpected encounter, Please contact the administrator',
                    );
                }
            }
            echo json_encode($result);
            break;
        case 'populateAnnouncement':
            session_start();
            require_once 'classes/Announcement.php';
            header('Content-Type: application/json');
            $id = $_POST['aid'];
            $ann = new Announcement();

            if ($ann->populateAnnouncementById($id)) {
                $result = array(
                    'error' => false,
                    'title' => $ann->getTitle(),
                    'message' => $ann->getMessage(),
                    'graphic' => $ann->getGraphic(),
                    'videoEmbLink' => $ann->getVideoEmbLink(),
                    'type' => $ann->getType()
                );
            } else {
                $result = array(
                    'error' => true
                );
            }
            echo json_encode($result);
            break;
        case 'delPost':
            session_start();
            require_once 'classes/Forum.php';
            header('Content-Type: application/json');
            $pid = $_POST['pid'];
            $f = new Forum();
            if ($f->deletePost($pid)) {
                $result = array(
                    'error' => false,
                    'message' => 'You have successfully delete the post'
                );
            } else {
                $result = array(
                    'error' => true,
                    'message' => 'Some unexpected technical problem occur'
                );
            }
            echo json_encode($result);
            break;
        case 'emailPromotional' :
            session_start();
            require_once 'classes/Announcement.php';
            require_once 'classes/Member.php';
            require_once 'classes/lib/swiftmalier/swift_required.php';
            header('Content-Type: application/json');
            $videoLink = $_POST['vLinks'];
            $to = $_POST['selects'];
            $aID = $_POST['aid'];
            $msg = $_POST['message'];
            $title = $_POST['title'];
            $ytube = $_POST['vLinks'];
            $content = $msg . '<br />Click <a href="http://localhost/RailwayWeb/announcementDetail.php?permalinkId=' . $_POST['aid'] . '"> here</a>for more information<br /><a href=' . $ytube . '>Click Here for Video Clips</a>';
            $ann = new Announcement();
            $m = new Member();
            $memberArray = $m->getAllMemberEmail();
            $result = array();
            if ($to == 1) {
                $result = array(
                    'error' => false,
                    'message' => 'Successfully sent the email to the Staffs'
                );
            } else if ($to == 2) {
                while ($memberArray) {
                    $ann->sendEmail(array_pop($memberArray), $title, $content);
                }
                $result = array(
                    'error' => false,
                    'message' => 'Successfully sent the email to the Members'
                );
            } else if ($to == 3) {
                $result = array(
                    'error' => false,
                    'message' => 'Successfully sent the email'
                );
            } else {
                $result = array(
                    'error' => true,
                    'message' => 'Some technical problem occur, please call the technician to fix the issue'
                );
            }
            echo json_encode($result);
            break;
//        case 'schedulestatus':
//            session_start();
//            require_once 'classes/Seat.php';
//            require_once 'classes/Schedule.php';
//            $routeid = $_POST['routeid'];
//            $sch = new Schedule();
//            $seat = new Seat();
//            $totalCount = $sch->getTotalCountSchedule($routeid);
//            
//            break;
    }
} else {
    header('HTTP/1.0 404 Not Found');
    include '404.php';
    exit;
}
?>
